package com.leo.erp.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leo.erp.dao.OrganizationDao;
import com.leo.erp.dao.OrganizationMapper;
import com.leo.erp.dto.OrganizationExecution;
import com.leo.erp.entity.Organization;
import com.leo.erp.entity.User;
import com.leo.erp.enums.OrganizationStateEnum;
import com.leo.erp.service.LogService;
import com.leo.erp.service.OrganizationService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.StringUtil;
import com.leo.erp.util.TreeNode;

@Service
public class OrganizationServiceImpl implements OrganizationService{
	@Autowired
	private OrganizationMapper organizationMapper;
	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private LogService logService;

	@Override
	public List<TreeNode> getOrganizationTree(int currentId, int tenantId) {
		List<TreeNode> list=null;
        try{
            list = organizationDao.getNodeTree(currentId, tenantId);
        }catch(GlobalRuntimeException e){
            e.printStackTrace();
        }
        return list;
	}

	@Override
	public OrganizationExecution addOrganization(Organization organization)  throws GlobalRuntimeException{
		OrganizationExecution oe = new OrganizationExecution();
		//新增时间
		organization.setCreateTime(new Date());
		//修改时间
		organization.setUpdateTime(new Date());
	
		/**
         * 未指定父级机构的时候默认为根机构
         * */
		if(StringUtil.isEmpty(organization.getOrgParentNo())) {
			organization.setOrgParentNo("-1");//根机构父级编号 根机父级构编号默认为-1
			
		}
		/**
         * 修改的时候检测机构编号是否已存在
         * */
		if(StringUtil.isNotEmpty(organization.getOrgNo())) {
			Boolean flag = checkOrgNoIsExists(organization.getOrgNo());
			if(flag) {
				oe.setState(OrganizationStateEnum.ORGNO_EXISTS.getState());//2机构编号已存在
				return oe;
			}
		}
		
		int effectedNum = organizationMapper.insert(organization);
		if(effectedNum > 0) {
			logService.insertLog("机构", "新增" + organization.getOrgFullName().toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
			oe.setState(OrganizationStateEnum.SUCCESS.getState());
		}else {
			oe.setState(OrganizationStateEnum.OFFLINE.getState());
		}
		
		return oe;
	}

	private Boolean checkOrgNoIsExists(String orgNo) {
		QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("orgNo", orgNo);
		List<Organization> list = organizationMapper.selectList(queryWrapper);
		if(list.size() > 0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public OrganizationExecution findById(int orgId) {
		OrganizationExecution oe = new OrganizationExecution();
		QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("orgId", orgId);
		
		try {
			List<Organization> list = organizationMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				oe.setState(OrganizationStateEnum.SUCCESS.getState());
				Organization org = list.get(0);
				oe.setOrganization(org);
			}else {
				oe.setState(OrganizationStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return oe;
	}

	@Override
	public OrganizationExecution findByOrgNo(String orgNo) {
		OrganizationExecution oe = new OrganizationExecution();
		QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("orgNo", orgNo);
		queryWrapper.ne("orgStcd", "5");
		try {
			List<Organization> list = organizationMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				Organization org = list.get(0);
				oe.setState(OrganizationStateEnum.SUCCESS.getState());
				oe.setOrganization(org);
			}else {
				oe.setState(OrganizationStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return oe;
	}

	@Override
	public OrganizationExecution editOrganization(Organization organization) {
		OrganizationExecution oe =new OrganizationExecution();
		//修改时间
		organization.setUpdateTime(new Date());
		//session
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        User user = (User)request.getSession().getAttribute("user");
        //修改人
        organization.setUpdater(user == null ? null : user.getUserId());
        organization.setTenantId(user.getTenantId());
        organization.setCreator(user.getUserId());
        /**
         * 未指定父级机构的时候默认为根机构
         * */
		if(StringUtil.isEmpty(organization.getOrgParentNo())) {
			organization.setOrgParentNo("-1");//根机构父级编号 根机父级构编号默认为-1
			
		}
		/**
         * 修改的时候检测机构编号是否已存在
         * */
		if(StringUtil.isNotEmpty(organization.getOrgNo())) {
			Boolean flag = checkOrgNoIsExists(organization.getOrgNo());
			if(flag) {
				oe.setState(OrganizationStateEnum.ORGNO_EXISTS.getState());//2机构编号已存在
				return oe;
			}
		}
		try {
			int effectedNum = organizationMapper.updateById(organization);
			if(effectedNum > 0) {
				logService.insertLog("机构", "修改" + organization.getOrgFullName().toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				oe.setState(OrganizationStateEnum.SUCCESS.getState());
			}else {
				oe.setState(OrganizationStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return oe;
	}

	@Override
	public OrganizationExecution batchDeleteOrganizationByIds(String ids) {
		OrganizationExecution oe =new OrganizationExecution();
		String[] idArray = ids.split(",");
		try {
			int effectedNum = organizationDao.batchDeleteOrganizationByIds(idArray);
			if(effectedNum > 0) {
				oe.setState(OrganizationStateEnum.SUCCESS.getState());
			}else {
				oe.setState(OrganizationStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return oe;
	}
	
	
}
